package com.ttuproject.ttu.advice;

import com.ttuproject.ttu.exception.TTUException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: <br>将异常以设定的形式返回
 * @CreateDate: Created in 2020/6/12 11:58 <br>
 * @Author: admin
 */
@Slf4j
@ControllerAdvice
public class CommonExceptionHandler {
    /**
     * 自定义异常处理
     * @param e 自定义异常
     * @return ResponseEntity
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<ExceptionResult> handleException(TTUException e) {
        //  Advice em = e.getAdvice();
        return ResponseEntity.status(e.getAdvice().getCode()).body(new ExceptionResult(e.getAdvice()));
    }

    /**
     * 参数校验异常处理
     * @param e 异常
     * @return ResponseEntity
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<ExceptionResult> handleException(BindException e) {
        List<ObjectError> errorList = e.getAllErrors();
        List<ExceptionResult> list = new ArrayList<>();
        errorList.forEach(error -> list.add(new ExceptionResult(500, error.getDefaultMessage())));
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(list.get(0));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ExceptionResult> handler(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        List<ObjectError> errorList = result.getAllErrors();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ExceptionResult(500,errorList.get(0).getDefaultMessage()));
    }
}
